<template>
  <div class="addAndEditProjectContent">
    <!-- v-bind="{ layout: 'vertical' }" -->
    <a-form ref="formRef" v-bind="{ layout: 'vertical' }"  :model="formModel" :rules="rules"
      :disabled="disabled">
      <a-form-item has-feedback label="项目名称" name="name">
        <a-input v-model:value="formModel.name" autocomplete="off" />
      </a-form-item>
      <div class="subTitle">项目设置</div>
      <div style="display: flex; justify-content: space-between;flex-wrap: wrap;">
        <a-form-item has-feedback label="年级" name="grade" style="width: 200px">
          <minDatePicker v-model:value="formModel.grade" picker="year" :disabledDate="disabledDate"
            style="margin-right: 12px; width: 100%" />
        </a-form-item>
        <a-form-item has-feedback label="班级" name="gradeClass" style="width: 200px" v-if="formModel.grade">
          <a-select v-model:value="formModel.gradeClass" mode="multiple" style="width: 100%; margin-right: 12px"
            placeholder="不限班级">
            <a-select-option :value="item.id" v-for="item in newSelectStructure.gradeClass">{{ item.name
              }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item has-feedback label="项目类型" name="category" style="width: 200px">
          <a-select allowClear v-model:value="formModel.category" style="width: 100%; margin-right: 12px"
            placeholder="项目类型">
            <a-select-option :value="item.dictValue" v-for="item in newSelectStructure.category">{{ item.dictName
              }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item has-feedback label="项目模板" name="template" style="width: 200px">
          <a-select allowClear v-model:value="formModel.template" style="width: 100%; margin-right: 12px"
            placeholder="项目模板">
            <a-select-option :value="item.value" v-for="item in newSelectStructure['template']">{{ item.label
              }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item has-feedback label="相关课程" name="course" style="width: 200px">
          <!-- <a-select v-model:value="formModel.course" mode="multiple" style="width: 100%; margin-right: 12px"
            placeholder="相关课程">
            <a-select-option :value="item.dictValue" v-for="item in newSelectStructure.course">{{ item.dictName
              }}</a-select-option>
          </a-select> -->
					<a-select v-model:value="formModel.course" mode="multiple" style="width: 100%; margin-right: 12px"
					  placeholder="相关课程" show-search :filter-option="filterOption" :options="newSelectStructure.course"
						:field-names="{ label: 'dictName', value: 'dictValue'}">
					</a-select>
        </a-form-item>
        <a-form-item has-feedback label="成员总数" name="totalMemberLimit" style="width: 200px;">
          <div style="display: flex;align-items: center;">
            <a-input-number style="width: 100%;margin-right: 12px;" v-model:value="formModel.totalMemberLimit"
              autocomplete="off" />
            人
          </div>
        </a-form-item>
        <a-form-item has-feedback label="开发模型" name="devModel" style="width: 200px">
          <a-select v-model:value="formModel.devModel" style="width: 100%; margin-right: 12px" placeholder="开发模型">
            <a-select-option :value="item.dictValue" v-for="item in newSelectStructure.devModel">{{ item.dictName
              }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item has-feedback label="小组人数设置" name="groupMemberLimit" v-if="formModel.template == 1">
          <div style="display: flex;align-items: center;width:200px">
            <a-input-number style="width: 100%;margin-right: 12px;" v-model:value="formModel.groupMemberLimit" autocomplete="off" />
            <div style="width: 30px;text-align: right;">人</div>
          </div>
        </a-form-item>
        <div style="width: 200px"></div>
      </div>
      <div class="subTitle required">岗位人数设置</div>
      <a-form-item name="projectJobDTOList">
        <div style="display: flex; flex-direction: column; align-items: center">
          <div v-for="(item, index) in formModel.projectJobDTOList"
            style="display: flex;justify-content: space-between;align-items: center;width: 100%;">
            <a-form-item has-feedback label="岗位" name="gangwei">
              <a-input style="width: 200px" v-model:value="item.name" autocomplete="off" />
            </a-form-item>
            <a-form-item has-feedback label="招募人数" name="requiredNum" style="margin: 0 12px">
              <a-input-number style="width: 200px" v-model:value="item.requiredNum" autocomplete="off" />
            </a-form-item>
            <a-form-item has-feedback label="技能描述" name="skill">
              <a-input style="width: 200px" v-model:value="item.skill" autocomplete="off" />
            </a-form-item>
            <MinusCircleOutlined v-if="formModel.projectJobDTOList.length > 1"
              style="padding: 0 20px; font-size: 20px; cursor: pointer"
              @click="handleClick({ name: '弹窗_删除招募信息', index })" />
          </div>
          <PlusCircleOutlined v-if="!disabled" style="padding: 20px 0; font-size: 20px; cursor: pointer"
            @click="handleClick({ name: '弹窗_增加招募信息' })" />
        </div>
      </a-form-item>
      <!-- <div class="subTitle" v-if="formModel.template == 1">小组人数设置</div>
      <a-form-item has-feedback label="小组最多" name="groupMemberLimit" v-if="formModel.template == 1">
        <div style="display: flex;align-items: center;">
          <a-input-number style="width: 100%;margin-right: 12px;" v-model:value="formModel.groupMemberLimit" autocomplete="off" />
          <div style="width: 30px;text-align: right;">人</div>
        </div>
      </a-form-item> -->
      <a-form-item has-feedback label="项目目标" name="target">
        <a-textarea v-model:value="formModel.target" />
      </a-form-item>
      <a-form-item has-feedback label="项目描述" name="describe">
        <a-textarea v-model:value="formModel.describe" />
      </a-form-item>
      <a-form-item has-feedback label="报名时间" name="registrationStartTime">
        <minRangePicker style="width: 100%" picker="datetime" v-model:startTime="formModel.registrationStartTime"
          v-model:endTime="formModel.registrationEndTime" />
      </a-form-item>
      <a-form-item has-feedback label="项目周期" name="startTime">
        <minRangePicker style="width: 100%" picker="datetime" v-model:startTime="formModel.startTime"
          v-model:endTime="formModel.endTime" />
      </a-form-item>
      <a-form-item has-feedback label="项目难度" name="difficulty">
        <a-rate v-model:value="formModel.difficulty" />
      </a-form-item>
      <a-form-item has-feedback label="评分标准" name="scoreStandard">
        <a-textarea v-model:value="formModel.scoreStandard" />
      </a-form-item>
      <!-- <a-form-item has-feedback label="主指导老师" name="mainTeacherId">
        <a-select v-model:value="formModel.mainTeacherId" :options="newSelectStructure.coTeacherIds" placeholder="请选择"
          style="width: 100%" :field-names="{ label: 'name', value: 'id' }"></a-select>
      </a-form-item> -->
      <a-form-item has-feedback label="副指导老师" name="coTeacherIds">
        <a-select v-model:value="formModel.coTeacherIds" :field-names="{ label: 'name', value: 'id' }"

          :options="newSelectStructure.coTeacherIds" placeholder="请选择" mode="multiple" style="width: 100%"
          show-search :filter-option="coTeacherFilterOption"
          ></a-select>

      </a-form-item>

      <a-form-item has-feedback label="项目图片" name="coverImg">
        <minUploadImage :disabled="disabled" v-model="formModel.coverImg" v-model:previewImage="formModel.coverImgUrl"
          :customUploadImage="customUploadImage" />
      </a-form-item>
      
      <a-form-item v-if="!disabled" style="text-align: center;padding-top: 20px;">
        <a-button type="primary" @click="handleSubmit" :loading="loading">提交</a-button>
        <a-button style="margin-left: 20px" @click="handleCancel">取消</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup>
import { PlusCircleOutlined, MinusCircleOutlined } from '@ant-design/icons-vue'

import minDatePicker from '@/components/common/minDatePicker.vue'
import minRangePicker from '@/components/common/minRangePicker.vue'
import minUploadImage from '@/components/common/minUploadImage.vue'
import minMultipleUploadImage from '@/components/common/minMultipleUploadImage.vue'
import { ossUpload, teacherGradeClassFindAll, typeCategory, teacherList } from '@/request/addAndEditProject'
import { defineProps, ref, defineEmits, watch } from 'vue'
import { message } from 'ant-design-vue'

const filterOption = (input, option) => {
  return option.dictName.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};


const coTeacherFilterOption= (input, option) => {
  return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

const { modelValue, customUploadImage, rules, disabled, selectStructure, loading } = defineProps({
  modelValue: Object,
  selectStructure: {
    type: Object,
    default: {},
  },
  customUploadImage: {
    type: Function,
    default: async (info) => {
      let res = await ossUpload({
        file: info.file,
        dir: 'teacher/avatar',
      })
      if (res) return res.data
    },
  },
  rules: {
    type: Object,
    default: {
      name: [
        { required: true, message: '请输入', trigger: 'change', },
      ],
      grade: [
        { required: true, message: '请输入', trigger: 'change', },
      ],
      groupMemberLimit: [
        { required: true, message: '请输入', trigger: 'change', },
      ],
      category: [
        { required: true, message: '请选择', trigger: 'change', },
      ],
      template: [
        { required: true, message: '请选择', trigger: 'change', },
      ],
      course: [
        { required: true, message: '请选择', trigger: 'change', type: 'array' },
      ],
      totalMemberLimit: [
        { required: true, message: '请输入', trigger: 'change', },
      ],
      devModel: [
        { required: true, message: '请输入', trigger: 'change', },
      ],
      target: [
        { required: true, message: '请输入', trigger: 'change', },
      ],
      difficulty: [
        { required: true, message: '请输入', trigger: 'change', },
      ],
      describe: [
        { required: true, message: '请输入', trigger: 'change', },
      ],
      registrationStartTime: [
        { required: true, message: '请输入', trigger: 'change', },
      ],
      startTime: [
        { required: true, message: '请输入', trigger: 'change', },
      ],
      coverImg: [
        {  message: '请选择', trigger: 'change', },
      ],
      projectJobDTOList: [
        {
          async validator(_rule, value) {
            const isValid = value.every(item => item.name && item.requiredNum && item.skill);
            return isValid ? Promise.resolve() : Promise.reject('请完善岗位信息')
          }
          , trigger: 'change'
        },
      ],
    },
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  loading: {
    type: Boolean,
    default: false,
  },

})
const formRef = ref()
const teacherStructure = ref([])
const formModel = ref({ ...modelValue })
const newSelectStructure = ref({
  ...selectStructure,
  template: [{ label: '经典', value: 0 }, { label: '多组协作', value: 1 }]
})
const emit = defineEmits(['handleSubmit', 'handleCancel'])

watch(() => modelValue, (newval) => {
  formRef?.value?.resetFields()
  formModel.value = { ...newval }
})
watch(() => selectStructure, (newval) => {
  newSelectStructure.value = {
    ...newSelectStructure.value,
    ...newval,
  }
})

watch(() => formModel.value.coverImg, async (newval) => {
	formRef.value.validateFields('coverImg')
})

const gradeShow =  async () => {
  let res = await teacherGradeClassFindAll({ 'search_AND_EQ_grade.year': formModel.value.grade })
  if (!res.data) return
  formModel.value.gradeClass = formModel.value.gradeClass ? [...formModel.value.gradeClass] : []
  newSelectStructure.value.gradeClass = res.data
}
watch(() => formModel.value.grade, async (newval) => {
  gradeShow()
})
const firstShow = async () => {
  let res = {
    类型: await typeCategory({ field: 'project_category' }),
    课程: await typeCategory({ field: 'course_category' }),
    开发模型: await typeCategory({ field: 'dev_model' }),
    教师列表: await teacherList()
  }
  if (res['类型']) newSelectStructure.value.category = res['类型'].data
  if (res['课程']) newSelectStructure.value.course = res['课程'].data
  if (res['开发模型']) newSelectStructure.value.devModel = res['开发模型'].data
	if (res['教师列表']) newSelectStructure.value.coTeacherIds = res['教师列表'].data
  if (formModel.value.grade) gradeShow()
}
firstShow()
const disabledDate = (time) => {
  return new Date(`${new Date().getFullYear() - 6}/12/31`).getTime() > time.valueOf()
}

const handleSubmit = async () => {
  let v = await formRef.value.validate().catch(err => false)
	if (!v) return message.error('请检查表单数据')
  emit('handleSubmit', {
    ...formModel.value,
  })
}
const handleCancel = () => {
  emit('handleCancel')
}

const handleClick = async ({ name, record, index }) => {
  switch (name) {
    case '弹窗_增加招募信息':
      formModel.value.projectJobDTOList.push({})
      break
    case '弹窗_删除招募信息':
      formModel.value.projectJobDTOList.splice(index, 1)
      break
  }
}
</script>

<style lang="scss" scoped>
.subTitle {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 10px;
}
.required {
    position: relative;
    /* padding-left: 30rpx; */
}
.required::before {
    content: '*';
    font-size: 16px;
    color: red;
    position: absolute;
    top: 0;
    bottom: 0;
    left: -10px;
    margin: auto;
    display: flex;
    align-items: center;
}
</style>